package com.jindi.appuser.common;

import java.io.File;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: duanj
 * Date: 2018-01-10
 * Time: 9:11
 * Description:
 */
public class ReadFromFile {

    public static int getSize(String fileName) {
        File file = new File(fileName);
        if(!file.exists()){
            return 0;
        }
        InputStream in = null;
        try {
            System.out.println("以字节为单位读取文件内容，一次读多个字节：");
            // 一次读多个字节
            in = new FileInputStream(fileName);
            int size1=in.available();
            return size1;
        } catch (Exception e1) {
            e1.printStackTrace();
            return 0;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    public static byte[] readFileByBytes(String fileName,int start,int size) {
        File file = new File(fileName);
        if(!file.exists()){
            return null;
        }
        InputStream in = null;
        try {
            System.out.println("以字节为单位读取文件内容，一次读多个字节：");
            // 一次读多个字节
            in = new FileInputStream(fileName);
            int byteread = 0;
            int size1=in.available();
            if(size1<size){
                size = size1-start;
            }
            byte[] tempbytes = new byte[size];
            in.skip(start);
            // 读入多个字节到字节数组中，byteread为一次读入的字节数
            in.read(tempbytes);
            System.out.write(tempbytes, 0, byteread);
            return tempbytes;
        } catch (Exception e1) {
            e1.printStackTrace();
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    }
    /**
     * 显示输入流中还剩的字节数
     *
     * @param in
     */
    private static void showAvailableBytes(InputStream in) {
        try {
            System.out.println("当前字节输入流中的字节数为:" + in.available());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
